package cn.zhouyafeng.itchat4j.demo.demo2;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import cn.zhouyafeng.itchat4j.beans.*;
import cn.zhouyafeng.itchat4j.resultBeans.Results;
import cn.zhouyafeng.itchat4j.resultBeans.TulingConfig;
import cn.zhouyafeng.itchat4j.resultBeans.TulingResult;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.DownloadTools;

/**
 * 图灵机器人2.0示例
 *
 * @version 2.0
 */
public class TulingRobot implements IMsgHandlerFace {
    Logger logger = Logger.getLogger("TulingRobot");
    MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
    String url = "http://openapi.tuling123.com/openapi/api/v2";
    String apiKey = TulingConfig.robotKey1; // 这里是我申请的图灵机器人API接口，每天只能100次调用，建议自己去申请一个，免费的:)
    private static Core core = Core.getInstance();

    @Override
    public String textMsgHandle(BaseMsg msg) {
        String result = "";
        String text = msg.getText();

        //处理对方想找机器人还是真人
        if (!TulingConfig.personStartWith.equals("") && text.startsWith(TulingConfig.personStartWith)) {
            return null;
        }

        if (text.startsWith(TulingConfig.robotStartWith)) {
            return getTulingResponse(msg, result, text);
        }

        return null;

    }

    private String getTulingResponse(BaseMsg msg, String result, String text) {
        //将消息封装为图灵2.0可接受的json格式
        ToTuling toTuling = new ToTuling();
        InputText inputText = new InputText();
        inputText.setText(text);
        Perception perception = new Perception();
        perception.setInputText(inputText);
        UserInfo userInfo = new UserInfo();
        userInfo.setApiKey(apiKey);
        userInfo.setUserId("123456");
        toTuling.setPerception(perception);
        toTuling.setUserInfo(userInfo);
        String paramStr = JSON.toJSONString(toTuling);
        System.out.println("paramStr:      " + paramStr);

        try {
            HttpEntity entity = myHttpClient.doPost(url, paramStr);
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("result:      " + result);


            TulingResult tulingResult = JSON.parseObject(result, TulingResult.class);
            String intent = tulingResult.getIntent();
            String code = JSON.parseObject(intent).getString("code");
            List<Results> results = tulingResult.getResults();
            String values = results.get(0).getValues();
            String sendText = JSON.parseObject(values).getString("text");

            //延迟回复时间
            Integer fixedTime = new Integer(TulingConfig.fixedTime);
            Integer contentTime = new Integer(TulingConfig.contentTime);
            Thread.sleep(sendText.length() * contentTime + fixedTime);


            result = sendText;
            if (code.equals("4003")) {
                apiKey = TulingConfig.robotKey2;
                System.out.println("机器人达到次数限制, 更换机器人");
                textMsgHandle(msg);
            } /*else {
                result = "处理有误,错误码:   " + code;
            }*/
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return result;
    }

    @Override
    public String picMsgHandle(BaseMsg msg) {
        return "收到图片";
    }

    @Override
    public String voiceMsgHandle(BaseMsg msg) {
        String fileName = String.valueOf(new Date().getTime());
        String voicePath = TulingConfig.saveUrl + "/voice" + File.separator + fileName + ".mp3";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath);
        return "收到语音";
    }

    @Override
    public String viedoMsgHandle(BaseMsg msg) {
        String fileName = String.valueOf(new Date().getTime());
        String viedoPath = TulingConfig.saveUrl + "/viedo" + File.separator + fileName + ".mp4";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath);
        return "收到视频";
    }

    public static void main(String[] args) {
        IMsgHandlerFace msgHandler = new TulingRobot();
        Wechat wechat = new Wechat(msgHandler, TulingConfig.saveUrl + "/login");
        wechat.start();
    }

    @Override
    public String nameCardMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void sysMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
    }

    @Override
    public String verifyAddFriendMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String mediaMsgHandle(BaseMsg msg) {
        // TODO Auto-generated method stub
        return null;
    }

}
